package com.dhh.sky.service;

import java.util.List;
import org.json.JSONObject;
import android.content.Intent;
import android.util.Log;
import com.dhh.sky.R;
import com.dhh.sky.SDAApplication;
import com.dhh.sky.model.Operation;
import com.dhh.sky.model.SkyDriveObject;
import com.dhh.sky.util.Constant;
import com.dhh.sky.util.JsonKeys;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationException;
import com.microsoft.live.LiveOperationListener;

public class MoveOperationService extends BasicOperationService{
	public MoveOperationService(){
		super(Constant.SERVICE_NAME_MOVE);
	}

	@Override
	protected void doOperation(Intent intent) {
		message = getString(R.string.msg_error_move);
		try{
			move();
		}catch(Exception e){
			Log.e(Constant.TAG, e.getMessage(), e);
		}
	}
	
	private void move(){
		if(next()){  
			path = op.getTarget();
			doMove(op.getPath(),path);
			oManager.removeOperation(op.getPath(), Operation.OP_MOVE); 
		}
	}
	
	private boolean next(){
		boolean flag = false;
		List<Operation> ops = oManager.getOperationReady(Operation.OP_MOVE);
		if(ops.size()>0){
			flag = true;
			op = ops.get(0);
			Log.d(Constant.TAG, "Move next(): "+op.getPath());
		}
		return flag;
	}
	
	private boolean doMove(String id,String folder){
		boolean flag = false;
		try{
	        mClient = ((SDAApplication) getApplication()).getConnectClient();
	        mClient.moveAsync(id, folder, new LiveOperationListener(){
				@Override
				public void onComplete(LiveOperation operation) {
					JSONObject result = operation.getResult();
					boolean succ = !result.has(JsonKeys.ERROR);
					if(succ){
						SkyDriveObject file = SkyDriveObject.create(result);
						fManager.delFile(file.getId());
						fManager.addFile(file);
					}
					
					response(succ,message,path);					
					move();
				}

				@Override
				public void onError(LiveOperationException exception,LiveOperation operation){
					response(false,message,path);
					move();
				}
			});
		}catch(Exception e){
			Log.e(Constant.TAG, e.getMessage(), e);
		}
		return flag;
	}

}
